package cn.ljy.authority.service.impl;

import cn.ljy.authority.config.security.UserUtil;
import cn.ljy.authority.dao.mapper.SysDailyTypeMapper;
import cn.ljy.authority.model.SysDaily;
import cn.ljy.authority.model.SysFileResource;
import cn.ljy.authority.model.query.SysDailyQuery;
import cn.ljy.authority.service.SysDailyService;
import cn.ljy.common.exception.model.MyWebException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

@Service
//@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor= MyRollBackException.class)
@Validated//表示开启sprint的校检框架，会自动扫描方法里的@Valid（@Valid注解一般写在接口即可）
@Slf4j
public class ISysDailyService extends IBaseService<SysDaily, SysDailyQuery> implements SysDailyService {

    @Autowired
    private SysDailyTypeMapper mapper;

    //添加关联属性
    private void setParam(SysDaily sysDaily){
        SysFileResource sysFileResource=sysDaily.getFileResource();
        if(sysDaily.getFileResource()!=null){
            //获取资源的绝对网址
            sysFileResource.setFileHttpUrl(super.getFileResourceWebUrl(sysFileResource.getFileUrl()));
        }
    }

    @Override
    protected void afterGet(SysDaily sysDaily) {
        //设置关联属性
        this.setParam(sysDaily);
    }

    @Override
    protected void afterFindAll(List<SysDaily> list) {
        for(SysDaily sysDaily:list){
            //设置关联属性
            this.setParam(sysDaily);
        }
    }

    @Override
    protected void beforeSaveOrUpdate(SysDaily sysDaily) {
        if(sysDaily.getDailyType()==null||sysDaily.getDailyType().getId()==null){
            throw new MyWebException("验证失败：所属类别信息不能为空");
        }
        //设置有用户信息
        sysDaily.setAuthor(UserUtil.getLoginUser());
    }


    @Override
    protected void beforeSave(SysDaily sysDaily) {
        if(sysDaily.getDisplay()==null){
            sysDaily.setDisplay(true);
        }
        if(sysDaily.getFileResource().getId()==null){
            throw new MyWebException("验证失败：标题图片对应的资源id不能为空");
        }
    }

    @Override
    protected void beforeUpdate(SysDaily sysDaily) {
        if(sysDaily.getLastAuthor()==null||sysDaily.getLastAuthor().getId()==null){
            throw new MyWebException("验证失败：作者信息不能为空");
        }
        if(sysDaily.getFileResource()!=null&&sysDaily.getFileResource().getId()==null){
            throw new MyWebException("验证失败：标题图片对应的资源id不能为空");
        }
    }
}
